package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.common.constant.MessageConstant;
import com.atguigu.common.entity.Result;
import com.atguigu.service.ReportService;
import com.atguigu.vo.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    ReportService reportService;

    /**
     *返回Result(flag,message,data):data=Map<String,Object>
     *     map：key             value
     *          months          List<String>   (["2018-12","2019-01","2019-02","2019-03","2019-04","2019-05"])
     *          memberCount     List<Integer>  ([5, 20, 36, 40, 50, 60])
     */
    @GetMapping("/getMemberReport")
    public Result getMemberReport(){
        //获取日历对象
        Calendar calendar = Calendar.getInstance();
        //根据当前时间 获取前十二个月的日历
        calendar.add(Calendar.MONTH,-12);
        //前十二个月的集合
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH,1);
            list.add(new SimpleDateFormat("yyyy-MM").format(calendar.getTime()));
        }
        MonthMemberVo monthMemberVo = new MonthMemberVo();
        monthMemberVo.setMonths(list);
        //查询前十二个月注册的会员数量
        List<Integer> memberCount = reportService.getMemberMonth(list);
        monthMemberVo.setMemberCount(memberCount);
        return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,monthMemberVo);
    }

    @GetMapping("/getSetmealReport")
    public Result getSetmealReport(){
        List<SetmealNameVo> nameVos = reportService.findSetmealAndOrder();
        List<String> names = new ArrayList<>();
        for (SetmealNameVo nameVo : nameVos) {
            names.add(nameVo.getName());
        }
        SetmealListVo setmealListVo = new SetmealListVo();
        setmealListVo.setNames(names);
        setmealListVo.setSetmealNameVos(nameVos);
        return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,setmealListVo);
    }

    @GetMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        BusinessReportDataVo dataVo = reportService.getBusinessReportData();
        return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,dataVo);
    }

    @GetMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        //远程调用获取数据
        BusinessReportDataVo result = reportService.getBusinessReportData();
        //读取模板文件
        String templatePath = request.getSession().getServletContext().getRealPath("template")
               + File.separator + "report_template.xlsx";
        try {
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(new File(templatePath)));
            importWorkbook(result, xssfWorkbook);
            //通过输出流下载
            ServletOutputStream outputStream = response.getOutputStream();
            //下载
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");
            xssfWorkbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            xssfWorkbook.close();
            return new Result(true,"success");
        } catch (IOException e) {
            return new Result(false,MessageConstant.EXPORT_BUSINESS_REPORT_FAIL);
        }
    }

    private void importWorkbook(BusinessReportDataVo result, XSSFWorkbook xssfWorkbook){
        //获取第一个工作表
        XSSFSheet sheetAt = xssfWorkbook.getSheetAt(0);
        XSSFRow row = sheetAt.getRow(2);
        row.getCell(5).setCellValue(result.getReportDate());//日期
        row = sheetAt.getRow(4);
        row.getCell(5).setCellValue(result.getTodayNewMember());
        row.getCell(7).setCellValue(result.getTotalMember());
        row = sheetAt.getRow(5);
        row.getCell(5).setCellValue(result.getThisWeekOrderNumber());
        row.getCell(7).setCellValue(result.getThisMonthOrderNumber());
        row = sheetAt.getRow(7);
        row.getCell(5).setCellValue(result.getTodayOrderNumber());
        row.getCell(7).setCellValue(result.getTodayVisitsNumber());
        row = sheetAt.getRow(8);
        row.getCell(5).setCellValue(result.getThisWeekOrderNumber());
        row.getCell(7).setCellValue(result.getThisWeekVisitsNumber());
        row = sheetAt.getRow(9);
        row.getCell(5).setCellValue(result.getThisMonthOrderNumber());
        row.getCell(7).setCellValue(result.getThisMonthVisitsNumber());
            /*
            新增会员数		总会员数
            本周新增会员数		本月新增会员数
            预约出游数据统计
            今日预约数		今日出游数
            本周预约数		本周出游数
            本月预约数		本月出游数
            热门套餐
            套餐名称	预约数量	占比	备注
             */
        List<HotSetmealVo> hotSetmeal = result.getHotSetmeal();
        Integer num = 12;
        for (HotSetmealVo hotSetmealVo : hotSetmeal) {
            row = sheetAt.getRow(num);
            row.getCell(4).setCellValue(hotSetmealVo.getName());
            row.getCell(5).setCellValue(hotSetmealVo.getSetmeal_count());
            row.getCell(6).setCellValue(hotSetmealVo.getProportion());
            num++;
        }
    }
}
